const router = require('koa-router')()
const DB = require('../other/DB');
const uuid = require('uuid').v1;


router.prefix('/api/inspect')

// 答题接口
const SaveData = async (ctx, value) => {
    var SearchParas = [ctx.userInfo.userName, ctx.request.body.topicId];
    var ans = await DB.query(`SELECT * FROM inspect WHERE user_id = ? AND topic_id = ?`, SearchParas);
    var id = null;
    if (ans[0] && ans[0].id) {
        id = ans[0].id;
        if (ans[0].draft == 1) {
            throw new Error('已经提交过，不可更改');
        }
    };
    var SaveData = {
        user_id: ctx.userInfo.userName,
        topic_id: ctx.request.body.topicId,
        code_content: ctx.request.body.codeContent,
        draft: value
    }
    var _T = new Date();
    if (value) {
        SaveData.submit_time = `${_T.getFullYear()}-${_T.getMonth() + 1}-${_T.getDate()} ${_T.getHours()}:${_T.getMinutes()}:${_T.getSeconds()}`;
    }
    if (id) {
        await DB.query(`UPDATE inspect SET ? WHERE id = ?`, [SaveData, id]);
    } else {
        SaveData.id = uuid();
        await DB.query(`INSERT INTO inspect SET ?`, [SaveData]);
    };
}

// 暂存代码
router.post('/save', async ctx => {
    await SaveData(ctx, 0);
    ctx.body = {
        message: '暂存成功'
    };
});

// 保存代码
router.post('/send', async ctx => {
    await SaveData(ctx, 1);
    ctx.body = {
        message: '提交成功'
    };
});



module.exports = router